<?php
class i_data{
    public function getSelOpt_LngList(){
        $_i18n = new classI18N();
        $lngList = $_i18n->getLngList();
        $lngActual = basename($_i18n->getActual(),'.inc.php');

        $result = '';
        foreach((array)$lngList as $lngName){
            if($lngActual==basename($lngName,'.inc.php'))
                $result.='<option value="'.basename($lngName,'.inc.php').'" selected="selected">'.basename($lngName,'.inc.php').'</option>';
            else
                $result.='<option value="'.basename($lngName,'.inc.php').'">'.basename($lngName,'.inc.php').'</option>';
        }

        return $result;
    }

    public function setLng(){
        $lngCode = trim($_REQUEST['lngCode']);
        if($lngCode!=''){
            $_i18n = new classI18N();
            return $_i18n->setActual($lngCode);
        }

        return -1;
    }

    public function getLngConstants(){
        //set language
        $_i18n = new classI18N();
        $language = $_i18n->getActual();
        if($language!=-1 and $language!='') require $language;
    }

    public function saveCfgMakeDB(){
        $this->createDataSession();

        if(!$this->testInputData())     return '_INPUTDATA_ERR_';
        if(!$this->testPasswords())     return '_PSSWDMATCH_ERR_';
        if(!$this->testDBConnection())  return '_DBCONNECTION_ERR_';
        if(!$this->testFilesAreWritable()) return '_FWRITABLE_ERR_';
        
        $this->saveHtaccessFile();
        $this->saveConfigFile();
        if($this->generateDBStructure()) return '_GENERATEDB_ERR_';

        return 1;
    }

    private function testFilesAreWritable(){
        if(!is_writable('.htaccess')) return false;
        if(!is_writable('definitions.inc.php')) return false;

        return true;
    }

    private function testInputData(){
        if(
            trim($_REQUEST['dbname'])     != '' and
            trim($_REQUEST['dbsocket'])   != '' and
            trim($_REQUEST['dbuser'])     != '' and
            trim($_REQUEST['admuser'])    != '' and
            trim($_REQUEST['admpsswd'])   != '' and
            trim($_REQUEST['admrepeatpsswd']) != ''
        )
            return 1;
        else return 0;
    }

    private function testPasswords(){
        if($_REQUEST['admpsswd'] == $_REQUEST['admrepeatpsswd'])
            return 1;
        else return 0;
    }

    private function testDBConnection(){
        $_db = new classDB();
        if($_db->open($_REQUEST['dbsocket'], $_REQUEST['dbuser'], $_REQUEST['dbpsswd'], $_REQUEST['dbname'])){
            $_db->close();
            return 1;
        }
        else return 0;
    }

    public function createDataSession(){
        $_sess = new classSessions();
        $_sess->open('ows_install_sess');

        $_sess->serializeIt(
            $_REQUEST['subdirectory']._USER_TEMP_DATA_ITEM_DELIMITER_.
            $_REQUEST['dbname']._USER_TEMP_DATA_ITEM_DELIMITER_.
            $_REQUEST['dbsocket']._USER_TEMP_DATA_ITEM_DELIMITER_.
            $_REQUEST['dbuser']._USER_TEMP_DATA_ITEM_DELIMITER_.
            $_REQUEST['admuser']
        );

    }
    
    public function loadDataSession(){
        $_sess = new classSessions();
        $result = explode(_USER_TEMP_DATA_ITEM_DELIMITER_, $_sess->open('ows_install_sess'));
                
        $arr['subdirectory']    = $result[0];
        $arr['dbname']          = $result[1];
        $arr['dbsocket']        = $result[2];
        $arr['dbuser']          = $result[3];
        $arr['admuser']         = $result[4];

        return $arr;
    }


    private function saveHtaccessFile(){
        $subdirectory = trim($_REQUEST['subdirectory'],' /');
        if($subdirectory!='') $subdirectory = '/'.$subdirectory;


        $data = '
            #AddType application/x-httpd-php5 .php
            RewriteEngine On

            # url kategorie
            RewriteRule ^.*/.*-([a-z]+)-S([0-9]+)-A([0-9]+)/$ '.$subdirectory.'/index.php?menu=def;def&product=$1;$2;0;$3&link=def [L]

            # url produktu + kategorie
            RewriteRule ^.*/.*-([a-z]+)-S([0-9]+)-A([0-9]+)/.*-P([0-9]+)\.html$ '.$subdirectory.'/index.php?menu=def;def&product=$1;$2;$4;$3&link=def [L]

            # url menu - textova novinka
            RewriteRule ^.*/.*-N([0-9]+)\.html$ '.$subdirectory.'/index.php?menu=1;$1&product=0;0;0;0&link=def [L]

            # url menu - clanok z hornho menu
            RewriteRule ^.*/.*-UA([0-9]+)\.html$ '.$subdirectory.'/index.php?menu=2;$1&product=0;0;0;0&link=def [L]

            # url kategorie novinka, vypredaj, akcia
            RewriteRule ^.*-T([0-9]+)-([a-z]+)-A([0-9]+)/$ '.$subdirectory.'/index.php?menu=def;def&product=$2;-$1;0;$3&link=def [L]

            # url kategorie novinka, vypredaj, akcia
            RewriteRule ^.*-T([0-9]+)-([a-z]+)-A([0-9]+)/.*-P([0-9]+)\.html$ '.$subdirectory.'/index.php?menu=def;def&product=$2;-$1;$4;$3&link=def [L]
        ';

        return file_put_contents('.htaccess', $data);
    }

    private function saveConfigFile(){
        $subdirectory = trim($_REQUEST['subdirectory'],' /');
        if($subdirectory!='') $subdirectory = '/'.$subdirectory.'/';

        $handle = @fopen("definitions.inc.php", "r");
        $buffer = "";
        if ($handle) {
            while (!feof($handle)) {
                $line = fgets($handle, 4096);

                //subdirectory
                if(stristr($line, "define('_SYSTEM_SUBDIRS_',") !== FALSE)
                    $line = "define('_SYSTEM_SUBDIRS_','".$subdirectory."');".$this->mycr();
                //dbname
                if(stristr($line, "define('_DB_NAME_',") !== FALSE)
                    $line = "define('_DB_NAME_','".$_REQUEST['dbname']."');".$this->mycr();
                //dbsocket
                if(stristr($line, "define('_DB_HOST_',") !== FALSE)
                    $line = "define('_DB_HOST_','".$_REQUEST['dbsocket']."');".$this->mycr();
                //dbuser
                if(stristr($line, "define('_DB_USER_',") !== FALSE)
                    $line = "define('_DB_USER_','".$_REQUEST['dbuser']."');".$this->mycr();
                //dbpsswd
                if(stristr($line, "define('_DB_PSSWD_',") !== FALSE)
                    $line = "define('_DB_PSSWD_','".$_REQUEST['dbpsswd']."');".$this->mycr();

                $buffer.= $line;                
            }
            fclose($handle);
            return file_put_contents("definitions.inc.php", $buffer);
        }

        return false;
    }

    private function generateDBStructure(){
        $_db = new classDB();
        if($_db->open($_REQUEST['dbsocket'], $_REQUEST['dbuser'], $_REQUEST['dbpsswd'], $_REQUEST['dbname'])){
            if(file_exists('install/db.sql')){
                $arr = explode(';', file_get_contents('install/db.sql'));

                foreach($arr as $sql_comm){
                    if(trim($sql_comm)!='') @mysql_query(trim($sql_comm));
                }
                
                $this->generateDefaultDBData();

                $_db->close();
                return 1;
            }
            else return 0;
        }
        else return 0;
    }
    
    private function generateDefaultDBData(){
        //admin
        $sql = 'select COUNT(*) from admins where A_Nick="'.$_REQUEST['admuser'].'"';
        $sql_res = mysql_fetch_row(mysql_query($sql));
        if($sql_res[0]=='0') 
            mysql_query('
                insert into admins (A_Nick, A_Passwd, A_Rights) 
                values ("'.$_REQUEST['admuser'].'", "'.sha1($_REQUEST['admpsswd']).'", "/1/2/3/4/5/6/")
            ');

        //first page
        $sql = 'select COUNT(*) from first_page';
        $sql_res = mysql_fetch_row(mysql_query($sql));
        if($sql_res[0]=='0')
            mysql_query('
                insert into first_page (page)
                values (1)
            ');

        //invoice options
        $sql = 'select COUNT(*) from invoice_options';
        $sql_res = mysql_fetch_row(mysql_query($sql));
        if($sql_res[0]=='0')
            mysql_query('
                INSERT INTO `invoice_options` (`Prefix`, `Expiration`, `Active`) VALUES ("'.date('Y').'/", 7, "1");
            ');
    }


    private function mycr() {
//        $os = php_uname('s');//get the os

//        if ($os == "Linux")
//            return "\n";
//        else if ($os == "Windows")
//            return "\r";

        //return "\n";
        return "
";
    }
}
?>
